package com.study.demo.schduleTask;

import com.study.demo.dto.Info;
import com.study.demo.dto.Pos;
import com.study.demo.repository.InfoRepository;
import com.study.demo.repository.PosRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class Task2 {
    @Value("${loader.rabbitmq.exchange}")
    private String exchange;
    @Value("${loader.rabbitmq.routingKey}")
    private String routingKey;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private InfoRepository infoRepository;
    @Autowired
    private PosRepository posRepository;

    @Scheduled(cron = "*/5 * * * * ?")
    public void saveToRabbitMq() {
        Pos pos = posRepository.findById(1);
        Integer position = pos.getPos();
        List<Info> infos =  infoRepository.searchByFlagAndPos(1, position);
        if (infos == null || infos.size() == 0) {
            return ;
        }
        for (Info info: infos) {
            rabbitTemplate.convertAndSend(exchange, routingKey, info);
        }
        position = infos.get(0).getId();
        posRepository.updatePos(position);

    }
}
